<!DOCTYPE html>
<html>
<head>
    <title>贪吃蛇</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background-color: #f0f0f0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            font-family: 'Courier New', Courier, monospace;
            padding: 20px;
        }
        
        .game-boy {
            background-color: #DFDFDF;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 
                0 0 0 2px #bbb,
                5px 5px 20px rgba(0,0,0,0.2);
            max-width: 95vw;
        }
        
        .screen-container {
            background-color: #8b8b8b;
            padding: 20px;
            border-radius: 10px 10px 30px 10px;
            margin-bottom: 20px;
        }
        
        canvas {
            background-color: #9ca04c;
            border-radius: 3px;
            image-rendering: pixelated;
        }
        
        .score {
            color: #306230;
            font-size: 24px;
            text-align: center;
            margin: 10px 0;
            text-shadow: 1px 1px 0 rgba(255,255,255,0.5);
        }
        
        .controls {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
        }
        
        .d-pad {
            width: 150px;
            height: 150px;
            position: relative;
            margin: 10px;
        }
        
        .d-pad button {
            position: absolute;
            width: 50px;
            height: 50px;
            background: #333;
            border: none;
            color: white;
            cursor: pointer;
            border-radius: 5px;
            box-shadow: 0 4px 0 #222;
            transition: all 0.1s;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
        }
        
        .d-pad button:active {
            transform: translateY(4px);
            box-shadow: 0 0 0 #222;
        }
        
        .d-pad .up { top: 0; left: 50px; border-radius: 5px 5px 0 0; }
        .d-pad .right { top: 50px; left: 100px; border-radius: 0 5px 5px 0; }
        .d-pad .down { top: 100px; left: 50px; border-radius: 0 0 5px 5px; }
        .d-pad .left { top: 50px; left: 0; border-radius: 5px 0 0 5px; }
        
        .action-buttons {
            display: flex;
            gap: 30px;
            margin-top: 10px;
        }
        
        .action-buttons button {
            background: #A93671;
            border: none;
            color: white;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            cursor: pointer;
            box-shadow: 0 4px 0 #722448;
            transition: all 0.1s;
            font-size: 14px;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
        }
        
        .action-buttons button:active {
            transform: translateY(4px);
            box-shadow: 0 0 0 #722448;
        }
        
        .game-title {
            font-size: 12px;
            color: #666;
            text-align: center;
            margin-top: 15px;
            letter-spacing: 1px;
        }
        
        @media (max-width: 768px) {
            .game-boy {
                transform: scale(0.9);
            }
            
            canvas {
                width: 280px;
                height: 280px;
            }
            
            .d-pad {
                transform: scale(1.1);
            }
            
            .action-buttons button {
                width: 70px;
                height: 70px;
            }
        }
        
        @media (max-width: 380px) {
            .game-boy {
                transform: scale(0.8);
            }
        }
    </style>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body>
    <div class="game-boy">
        <div class="screen-container">
            <canvas id="gameCanvas" width="300" height="300"></canvas>
        </div>
        <div class="controls">
            <div class="d-pad">
                <button class="up">↑</button>
                <button class="right">→</button>
                <button class="down">↓</button>
                <button class="left">←</button>
            </div>
            <div class="action-buttons">
                <button id="pauseBtn">暂停</button>
                <button id="resetBtn">重置</button>
            </div>
        </div>
        <div class="game-title">SNAKE GAME v1.0</div>
    </div>

    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const gridSize = 20;
        const tileCount = canvas.width / gridSize;
        const scoreAreaHeight = 40;
        const baseSpeed = 200;
        
        let score = 0;
        let snake = [
            {x: 10, y: Math.floor(scoreAreaHeight/gridSize) + 2}
        ];
        let food = generateFood();
        let dx = 0;
        let dy = 0;
        let gameSpeed = baseSpeed;
        let isGameOver = false;
        let isGameWon = false;
        let isPaused = false;

        document.addEventListener('keydown', changeDirection);

        function changeDirection(event) {
            const LEFT_KEY = 37;
            const RIGHT_KEY = 39;
            const UP_KEY = 38;
            const DOWN_KEY = 40;

            const keyPressed = event.keyCode;
            const goingUp = dy === -1;
            const goingDown = dy === 1;
            const goingRight = dx === 1;
            const goingLeft = dx === -1;

            if (keyPressed === LEFT_KEY && !goingRight) {
                dx = -1;
                dy = 0;
            }
            if (keyPressed === UP_KEY && !goingDown) {
                dx = 0;
                dy = -1;
            }
            if (keyPressed === RIGHT_KEY && !goingLeft) {
                dx = 1;
                dy = 0;
            }
            if (keyPressed === DOWN_KEY && !goingUp) {
                dx = 0;
                dy = 1;
            }
        }

        function drawGame() {
            if (isPaused) return;
            
            if (!isGameOver) {
                const head = {x: snake[0].x + dx, y: snake[0].y + dy};
                snake.unshift(head);

                if (head.x === food.x && head.y === food.y) {
                    score += 10;
                    food = generateFood();
                    gameSpeed = Math.max(50, baseSpeed - Math.floor(score / 50) * 10);
                    
                    if (score >= 180) {
                        isGameOver = true;
                        isGameWon = true;
                    }
                } else {
                    snake.pop();
                }

                if (checkGameOver()) {
                    isGameOver = true;
                    isGameWon = false;
                }
            }

            // 清空画布
            ctx.fillStyle = '#9ca04c';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制分数区域和边界线
            ctx.fillStyle = 'rgba(156, 160, 76, 0.9)';
            ctx.fillRect(0, 0, canvas.width, scoreAreaHeight);
            
            // 绘制边界线
            ctx.fillStyle = '#306230';
            ctx.fillRect(0, scoreAreaHeight - 2, canvas.width, 2);

            // 绘制分数
            ctx.fillStyle = '#306230';
            ctx.font = '20px "Courier New"';
            ctx.textAlign = 'center';
            ctx.fillText(`分数: ${score}`, canvas.width/2, 25);

            // 绘制食物
            ctx.fillStyle = '#000000';
            ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize-2, gridSize-2);

            // 绘制蛇
            ctx.fillStyle = '#306230';
            snake.forEach(segment => {
                ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize-2, gridSize-2);
            });

            // 如果游戏结束，显示游戏结束文字
            if (isGameOver) {
                ctx.fillStyle = 'rgba(156, 160, 76, 0.8)';
                ctx.fillRect(0, canvas.height/2 - 60, canvas.width, 160);
                
                ctx.fillStyle = '#306230';
                ctx.font = 'bold 40px "Courier New"';
                ctx.textAlign = 'center';
                
                if (isGameWon) {
                    ctx.fillText('恭喜通关!', canvas.width/2, canvas.height/2);
                    ctx.font = '16px "Courier New"';
                    ctx.fillText('May the force be with you', canvas.width/2, canvas.height/2 + 40);
                } else {
                    ctx.fillText('GAME OVER', canvas.width/2, canvas.height/2);
                    ctx.font = '20px "Courier New"';
                    ctx.fillText(`最终得分: ${score}`, canvas.width/2, canvas.height/2 + 40);
                }
                
                ctx.fillText('按空格键重新开始', canvas.width/2, canvas.height/2 + 80);
                return;
            }

            if (!isGameOver) {
                setTimeout(drawGame, gameSpeed);
            }
        }

        function generateFood() {
            // 在安全区以下生成食物
            const minY = Math.ceil(scoreAreaHeight/gridSize);
            let newFood;
            
            do {
                newFood = {
                    x: Math.floor(Math.random() * tileCount),
                    y: Math.floor(Math.random() * (tileCount - minY)) + minY
                };
            } while (isFoodOnSnake(newFood)); // 如果食物在蛇身上，重新生成
            
            return newFood;
        }

        function isFoodOnSnake(food) {
            return snake.some(segment => 
                segment.x === food.x && segment.y === food.y
            );
        }

        function checkGameOver() {
            // 撞墙（包括顶部安全区）
            if (snake[0].x < 0 || snake[0].x >= tileCount || 
                snake[0].y < Math.floor(scoreAreaHeight/gridSize) || snake[0].y >= tileCount) {
                return true;
            }

            // 撞到自己
            for (let i = 1; i < snake.length; i++) {
                if (snake[i].x === snake[0].x && snake[i].y === snake[0].y) {
                    return true;
                }
            }
            return false;
        }

        function resetGame() {
            score = 0;
            snake = [{x: 10, y: Math.floor(scoreAreaHeight/gridSize) + 2}];
            dx = 0;
            dy = 0;
            gameSpeed = baseSpeed;
            isGameOver = false;
            isGameWon = false;
            isPaused = false;
            food = generateFood();
            updatePauseButton();
            drawGame();
        }

        // 添加空格键重启游戏
        document.addEventListener('keydown', function(event) {
            if (event.code === 'Space' && isGameOver) {
                resetGame();
            }
        });

        // 添加虚拟按键控制
        document.querySelector('.up').addEventListener('click', () => simulateKeyPress(38));
        document.querySelector('.right').addEventListener('click', () => simulateKeyPress(39));
        document.querySelector('.down').addEventListener('click', () => simulateKeyPress(40));
        document.querySelector('.left').addEventListener('click', () => simulateKeyPress(37));
        
        // 更新暂停按钮文字
        function updatePauseButton() {
            const pauseBtn = document.getElementById('pauseBtn');
            pauseBtn.textContent = isPaused ? '继续' : '暂停';
        }
        
        // 暂停按钮事件处理
        document.getElementById('pauseBtn').addEventListener('click', () => {
            isPaused = !isPaused;
            updatePauseButton();
            if (!isPaused && !isGameOver) {
                drawGame();
            }
        });
        
        // 重置按钮事件处理
        document.getElementById('resetBtn').addEventListener('click', resetGame);
        
        function simulateKeyPress(keyCode) {
            changeDirection({ keyCode: keyCode });
        }

        // 添加触摸事件支持
        document.addEventListener('touchstart', function(e) {
            e.preventDefault(); // 防止双击缩放
        }, { passive: false });
        
        // 优化移动端按钮响应
        const buttons = document.querySelectorAll('button');
        buttons.forEach(button => {
            button.addEventListener('touchstart', function(e) {
                e.preventDefault();
                this.click();
            });
        });

        // 开始游戏
        drawGame();
    </script>
</body>
</html>
